package org.example.leetcode.interview.slide;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class LC0056 {
    public int[][] merge(int[][] intervals) {
        List<int[]> ans = new LinkedList<>();
        Arrays.sort(intervals, (x, y) -> Integer.compare(x[0], y[0]));
        int left = intervals[0][0];
        int right = intervals[0][1];
        for (int i = 1; i < intervals.length; i++) {
            // 左边界比右边界大
            if (intervals[i][0] > right) {
                ans.add(new int[]{left, right});
                left = intervals[i][0];
                right = intervals[i][1];
            } else {
                // 更新右边界
                right = Math.max(right, intervals[i][1]);
            }
        }

        ans.add(new int[] {left, right});
        return ans.toArray(new int[ans.size()][]);
    }
}
